﻿using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace QuantBox
{
    [DataContract]
    internal class HDataSettings
    {
        [DataMember]
        public byte Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public string Url { get; set; }

        [DataMember]
        public string LogPrefix { get; set; }
        [DataMember]
        public string DataCenterHost { get; set; }
        [DataMember]
        public string TickFileHost { get; set; }
        [DataMember]
        public string ChainDataPath { get; set; }

        private static string GetSettingsPath()
        {
            return QBHelper.GetConfigPath("QuantBoxData");
        }

        private static HDataSettings Default()
        {
            return new HDataSettings {
                Id = QuantBoxConst.PIdHisData,
                Name = "QuantBoxData",
                Description = "QB数据",
                Url = "www.quantbox.com",
                DataCenterHost = "http://data.quantbox.cn/",
                TickFileHost = "http://data.quantbox.cn/",
                LogPrefix = "qb_data"
            };
        }

        public void Save()
        {
            var json = JsonConvert.SerializeObject(this, Formatting.Indented);
            File.WriteAllText(GetSettingsPath(), json);
        }

        public void Reload() 
        {
            var exists = JsonConvert.DeserializeObject<HDataSettings>(File.ReadAllText(GetSettingsPath()));
            DataCenterHost = exists.DataCenterHost;
            TickFileHost = exists.TickFileHost;
        }

        public static HDataSettings Load()
        {
            var path = GetSettingsPath();
            var settings = Default();
            if (File.Exists(path)) {
                var exists = JsonConvert.DeserializeObject<HDataSettings>(File.ReadAllText(path));
                exists.Id = settings.Id;
                exists.Name = settings.Name;
                exists.Description = settings.Description;
                exists.Url = settings.Url;
                if (string.IsNullOrEmpty(exists.DataCenterHost)) {
                    exists.DataCenterHost = settings.DataCenterHost;
                }
                settings = exists;
            }
            settings.Save();
            return settings;
        }
    }
}